<?php
namespace app\index\logic;
use think\Db;

class Chapter
{
    public function getMaxChapnumInfo($nid)
    {
        $where[] = ['novel_id','=',$nid];

        $field      = 'name,chapter_no,update_time';
        $orderBy    = ['chapter_no'=>'DESC'];

        $Chapter = \think\facade\App::model('Chapter');
        $result = $Chapter->getOne($where,$field,$orderBy);

        return $result ? $result : [];
    }

    public function getList($params)
    {
        $params['page']     = isset($params['Pages']) ? $params['Pages'] : 1;
        $params['limit']    = isset($params['Size']) ? $params['Size'] : 20;

        $condition[] = ['novel_id', 'eq', 'gt:0','nid'];

        $where   = buildQueryCondition($condition, $params);

        $orderBy = [ 'chapter_no'=>'ASC', 'id' => 'ASC'];

        $ChapterModel = \think\facade\App::model('Chapter', 'model');
        $list = $ChapterModel->getList($where, 'chapter_no,is_pay', $params['page'], $params['limit'], $orderBy );

        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['title'] = '第'.$v['chapter_no'].'章';
            }
        }

        $result['total']    = $ChapterModel->getTotalNumber($where);
        $result['list']     = $list;

        return $result;
    }

    public function getInfo($params)
    {
        $table = "novel_chapter_content_" . intval(substr($params['nid'], -2));

        $where[] = ['novel_id','=',$params['nid']];
        $where[] = ['chapter_no','=',$params['chapter_no']];

        $record = Db::table($table)->where($where)->field('content')->findOrEmpty();
        if($record)
        {
            $chapter_total = Db::table('novel_chapter')->where('novel_id',$params['nid'])->count('id');
            $chapter = Db::table('novel_chapter')->where($where)->field('words,is_pay')->findOrEmpty();

            $record['is_pay']           = $chapter['is_pay'];
            $record['word_count']       = $chapter['words'];
            $record['prev_chapter_no']  = $params['chapter_no'] > 1 ? $params['chapter_no']-1 : 1;
            $record['next_chapter_no']  = $params['chapter_no'] < $chapter_total ? $params['chapter_no']+1 : 0;
            $record['chapter_no']       = $params['chapter_no'];
            $record['chapter_title']    = '第'.$params['chapter_no'].'章';
            $record['content']          = strlen($record['content']) > 1 ? formatChapterContent($record['content'],'<p>','</p>') : '';
        }

        return $record;
    }

}